import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:crop_your_image/crop_your_image.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'ocr_service.dart';

class UnifiedOcrPage extends StatefulWidget {
  final Uint8List imageData;

  const UnifiedOcrPage({super.key, required this.imageData});

  @override
  State<UnifiedOcrPage> createState() => _UnifiedOcrPageState();
}

class _UnifiedOcrPageState extends State<UnifiedOcrPage> {
  final OcrService _ocrService = OcrService();
  bool _isProcessing = false;
  final CropController _cropController = CropController();
  Size? _imageSize;

  @override
  void initState() {
    super.initState();
    _loadImageSize();
  }

  Future<void> _loadImageSize() async {
    try {
      final codec = await ui.instantiateImageCodec(widget.imageData);
      final frame = await codec.getNextFrame();
      setState(() {
        _imageSize = Size(
          frame.image.width.toDouble(),
          frame.image.height.toDouble(),
        );
      });
    } catch (e) {
      print('Failed to load image size: $e');
    }
  }

  Future<void> _recognizeCroppedArea() async {
    if (_isProcessing) return;

    setState(() => _isProcessing = true);

    // 显示加载提示
    EasyLoading.show(status: '处理中...');

    // 调用crop()方法来获取裁剪结果
    _cropController.crop();
  }

  void _onCropped(CropResult result) async {
    if (result is CropSuccess) {
      try {
        // 直接使用裁剪后的图片数据进行OCR识别
        final ocrResult = await _ocrService.recognizeTextFromBytes(
          result.croppedImage,
        );

        EasyLoading.dismiss();
        _showOcrDialog(ocrResult);
      } catch (e) {
        print('OCR识别失败: $e');
        EasyLoading.dismiss();
        _showOcrDialog('识别失败，请重试');
      } finally {
        setState(() => _isProcessing = false);
      }
    } else if (result is CropFailure) {
      print('裁剪失败: ${result.cause}');
      EasyLoading.dismiss();
      _showOcrDialog('裁剪失败，请重试');
      setState(() => _isProcessing = false);
    }
  }

  void _showOcrDialog(String recognizedText) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Row(
            children: [
              Icon(Icons.text_fields, color: Colors.blue),
              SizedBox(width: 8),
              Text('OCR识别结果'),
            ],
          ),
          content: SizedBox(
            width: double.maxFinite,
            height: 300,
            child: SingleChildScrollView(
              child: Text(
                recognizedText.isEmpty ? '暂无识别结果' : recognizedText,
                style: const TextStyle(fontSize: 16, height: 1.5),
              ),
            ),
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text('关闭'),
            ),
          ],
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        title: const Text('OCR识别'),
        backgroundColor: Colors.black,
        foregroundColor: Colors.white,
        actions: [
          IconButton(
            onPressed: _recognizeCroppedArea,
            icon: const Icon(Icons.text_fields),
            tooltip: 'OCR识别',
          ),
        ],
      ),
      body: InteractiveViewer(
        panEnabled: true,
        scaleEnabled: true,
        minScale: 0.01,
        maxScale: 100,
        child: Crop(
          initialRectBuilder: _imageSize != null
              ? InitialRectBuilder.withArea(
                  Rect.fromLTWH(
                    _imageSize!.width / 4,
                    _imageSize!.height / 4,
                    _imageSize!.width / 2,
                    _imageSize!.height / 2,
                  ),
                )
              : null,
          image: widget.imageData,
          controller: _cropController,
          onCropped: _onCropped,
          maskColor: Colors.black.withOpacity(0.6),
          withCircleUi: false,
        ),
      ),
    );
  }
}
